<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { getCategoryAllListService, getSubCategoryPageListService, addSubCategoryService, updateSubCategoryService, deleteSubCategoryService } from '@/apis/category'

//用户搜索时选中的分类id
const categoryId = ref('')

const categorys = ref([])
const getAllCategory = async () => {
    const res = await getCategoryAllListService()
    categorys.value = res.data
}

const subCategories = ref([])
//分页条数据模型
const page = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(5)//每页条数


const getSubCategoryList = async () => {
    const params = {
        page: page.value,
        pageSize: pageSize.value,
        categoryId: categoryId.value ? categoryId.value : null
    }
    const res = await getSubCategoryPageListService(params)
    subCategories.value = res.data.items
    total.value = res.data.total
}
onMounted(() => {getSubCategoryList() ,getAllCategory()})

// 页数切换
const pageChange = (newPage) => {
    page.value = newPage
    getSubCategoryList()
}

//添加分类数据模型
const subCategory = ref({
    name: '',
    categoryId: '',
    categoryPic: ''
})

//控制添加分类弹窗
const dialogVisible = ref(false)
//控制标题展示
const title = ref('')

// 上传成功的回调函数
const uploadSuccess = (result) => {
    subCategory.value.categoryPic = result.data
    console.log(result.data);
}

const addSubCategory = async () => {
    await addSubCategoryService(subCategory.value)
    ElMessage.success("添加成功")
    getSubCategoryList()
    dialogVisible.value = false
}

//展示编辑弹窗
const showDialog = (row) => {
    dialogVisible.value = true
    title.value = '编辑分类'
    //数据拷贝
    subCategory.value.name = row.name
    subCategory.value.categoryId = row.categoryId
    subCategory.value.categoryPic = row.categoryPic
    subCategory.value.id = row.id
}

const updateSubCategory = async () => {
    await updateSubCategoryService(subCategory.value)
    ElMessage.success("修改成功")
    getSubCategoryList()
    dialogVisible.value = false
}
const deleteSubCategory = (row) => {
    ElMessageBox.confirm(
        '你确认删除该分类信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认
            await deleteSubCategoryService(row.id)
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            getSubCategoryList()
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const clearData = () => {
    subCategory.value.name = ""
    subCategory.value.categoryId = ""
    subCategory.value.categoryPic = ""
}


</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>商品分类</span>
                <div class="extra">
                    <el-button type="primary"
                        @click="dialogVisible = true; title = '添加分类'; clearData()">添加分类</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="所属分类：">
                <el-select placeholder="请选择" v-model="categoryId" class="custom-form-item">
                    <el-option v-for="c in categorys" :key="c.id" :label="c.name" :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getSubCategoryList">搜索</el-button>
                <el-button @click="categoryId = ''">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="subCategories" style="width: 100%">
            <el-table-column label="id" prop="id"> </el-table-column>
            <el-table-column label="分类名称" prop="name"></el-table-column>
            <el-table-column label="所属分类" prop="parentName"></el-table-column>
            <el-table-column label="分类图片" prop="categoryPic">
                <template v-slot="scope">
                    <img :src="scope.row.categoryPic" :alt="'图片' + scope.$index" style="width: 100px; height: 100px;">
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime"></el-table-column>
            <el-table-column label="更新时间" prop="updateTime"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteSubCategory(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination :total="total" @current-change="pageChange" :page-size="pageSize" background
                layout="prev, pager, next" />
        </div>

        <!-- 添加分类弹窗 -->
        <el-dialog v-model="dialogVisible" :title="title" width="30%">
            <el-form :model="subCategory" label-width="100px" style="padding-right: 30px">
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="subCategory.name" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="所属分类">
                    <el-select placeholder="请选择" v-model="subCategory.categoryId">
                        <el-option v-for="c in categorys" :key="c.id" :label="c.name" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类图片">
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :on-success="uploadSuccess">
                        <img v-if="subCategory.categoryPic" :src="subCategory.categoryPic" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">+</el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="title == '添加分类' ? addSubCategory() : updateSubCategory()"> 确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

/* 搜索框样式 */
.custom-form-item {
    /* 设置您需要的宽度、边距等样式 */
    width: 200px;
    /* 根据需要调整 */
    margin-right: 10px;
    /* 根据需要调整 */
}
</style>